package com.lhfeiyu.action.front.auction;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.action.common.CreditMoney;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.po.AuctionGoods;
import com.lhfeiyu.po.AuctionInst;
import com.lhfeiyu.po.AuctionProfession;
import com.lhfeiyu.po.AuctionProfessionOffers;
import com.lhfeiyu.po.base.BaseGoods;
import com.lhfeiyu.po.base.BaseGoodsPicture;
import com.lhfeiyu.po.base.BaseUser;
import com.lhfeiyu.po.base.BaseUserFund;
import com.lhfeiyu.service.AuctionGoodsService;
import com.lhfeiyu.service.AuctionInstService;
import com.lhfeiyu.service.AuctionProfessionOffersService;
import com.lhfeiyu.service.AuctionProfessionService;
import com.lhfeiyu.service.AuthCheckService;
import com.lhfeiyu.service.base.BaseFansService;
import com.lhfeiyu.service.base.BaseGoodsPictureService;
import com.lhfeiyu.service.base.BaseGoodsService;
import com.lhfeiyu.service.base.BaseUserFundService;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.Check;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.Result;
import com.lhfeiyu.util.base.RequestUtil;

@Controller
@RequestMapping(value="/ag")
public class AuctionGoodsAction {
	@Autowired
	private AuctionGoodsService agService;
	@Autowired
	private AuctionProfessionService apService;
	@Autowired
	private AuctionProfessionOffersService apoService;
	@Autowired
	private AuctionInstService aiService;
	@Autowired
	private BaseGoodsService goodsService;
	@Autowired
	private BaseGoodsPictureService gpService;
	@Autowired
	private AuthCheckService authCheckService;
	@Autowired
	private BaseUserFundService ufService;
	@Autowired
	private BaseFansService fansService;
	
	private static Logger logger = Logger.getLogger("R");

	@RequestMapping(value="/page/agList/{auctionSerial}")
	public ModelAndView professionGoods(ModelMap modelMap,HttpServletRequest request,
		@PathVariable String auctionSerial, @RequestParam(required=false) String r) {
		String path = Page.professionGoods;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/page/agList/"+auctionSerial;
				return Result.userSessionInvalid(modelMap, ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			Integer userId = sessionUser.getId();
			Map<String, Object> map = RequestUtil.getRequestParam(request);//自动获取所有参数（查询条件）
			map.put("auctionSerial", auctionSerial);//在URL路径中获取的参数不为被自动获取，需要手动存入paramMap
			Map<String, Object> resultMap = agService.professionGoods(map, sessionUser);
			modelMap.putAll(resultMap);
			json.put("auctionSerial", auctionSerial);
			
			if(Check.isNotNull(auctionSerial)){//专场保证金
				AuctionProfession profession = apService.selectBySerial(auctionSerial);
				if(null == profession){
					return new ModelAndView(Page.index, modelMap);
				}
				if(Check.isNotNull(profession.getPicPaths())){
					profession.setPicPaths(CommonGenerator.buildOSSZoom(profession.getPicPaths(), 420, 150));//@@_OSS_IMG_@@
				}
				json.put("ap", profession);
				modelMap.put("ap", profession);
				//检查保证金是否足够，不能则跳转到支付保证金页面
				if(profession.getTypeId() == 2){//需要保证金的专场
					BaseUserFund uf = ufService.selectUserFundByUserId(userId);
					if(null == uf){
						Result.failure(json, "您的资金账户存在异常，请联系客服人员", "uf_null");
						return new ModelAndView(path, modelMap);
					}
					modelMap = CreditMoney.checkCreditMoneyForAP(profession, modelMap, json, uf, path);
				}
			}
			modelMap.put("paramJson", json);
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/ag/page/agList/"+auctionSerial, modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/page/detail/{auctionGoodsId}")
	public ModelAndView professionGoodsDetail(ModelMap modelMap, HttpServletRequest request
			,@PathVariable Integer auctionGoodsId
			,@RequestParam(required=false) String r) {
		String path = Page.professionGoodsDetail;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser sessionUser = ActionUtil.checkSession4User(request.getSession());
			if(null == sessionUser){
				String jumpUrl = "/ag/page/detail/"+auctionGoodsId;
				return Result.userSessionInvalid(modelMap,  ActionUtil.buildPromoterUrl(jumpUrl, r));
			}
			Integer userId = sessionUser.getId();
			Map<String, Object> map = RequestUtil.getRequestParam(request);//自动获取所有参数（查询条件）
			map.put("auctionGoodsId", auctionGoodsId);
			AuctionGoods auctionGoods = agService.selectByCondition(map);
			if(null != auctionGoods){
				AuctionGoods newAuctionGoods = new AuctionGoods();
				newAuctionGoods.setId(auctionGoods.getId());
				Integer count = auctionGoods.getScansCount();
				if(null == count || count <= 0)count = 1;
				newAuctionGoods.setScansCount(++count);//更新访问量
				agService.updateByPrimaryKeySelective(newAuctionGoods);
			}
			List<AuctionProfessionOffers> apoList = apoService.selectListByCondition(map);
			int apoListSize = 0;
			if(Check.isNotNull(apoList))apoListSize = apoList.size();
			Integer goodsId = auctionGoods.getGoodsId();
			Integer auctionId = auctionGoods.getAuctionId();
			map.clear();
			map.put("auctionId", auctionId);
			AuctionProfession profession = apService.selectByCondition(map);
			List<AuctionGoods> allGoodsList = agService.selectListByCondition(map);
			map.clear();
			map.put("goodsId", goodsId);
			List<BaseGoodsPicture> picList = gpService.selectListByCondition(map);
			if(Check.isNotNull(picList)){
				for(BaseGoodsPicture pic : picList){
					if(Check.isNotNull(pic.getPicPath())){
						pic.setPicPath(CommonGenerator.buildOSSZoom(pic.getPicPath(), 360, 235));//@@_OSS_IMG_@@
					}
				}
			}
			BaseGoods goods = goodsService.selectByPrimaryKey(goodsId);
			if(profession.getTypeId() == 2){//需要保证金的专场
				BaseUserFund uf = ufService.selectUserFundByUserId(userId);
				if(null == uf){
					Result.failure(json, "您的资金账户存在异常，请联系客服人员", "uf_null");
					return new ModelAndView(path, modelMap);
				}
				modelMap = CreditMoney.checkCreditMoneyForAP(profession, modelMap, json, uf, path);
			}
			if(null != auctionGoods && null != profession){
				modelMap.put("auctionGoods", auctionGoods);
				modelMap.put("goodsList", allGoodsList);
				modelMap.put("picList", picList);
				modelMap.put("ap", profession);
				modelMap.put("apoList", apoList);
				modelMap.put("apoListSize", apoListSize);
				modelMap.put("goods", goods);
				json.put("ap", profession);
				json.put("auctionGoodsId", auctionGoodsId);
			}else{
				path = Page.auctionInst;
				modelMap.put("status", "done");
			}
			//检查关注情况
			fansService.checkFocus(json, sessionUser, profession.getUserId());
			modelMap.put("paramJson", json);
		}catch(Exception e){
			Result.catchError(e, logger, this.getClass().getName()+"/ag/page/detail/"+auctionGoodsId, modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/myAGList/{auctionId}")
	public ModelAndView myAGList(ModelMap modelMap,HttpServletRequest request,
			@PathVariable Integer auctionId, @RequestParam(required=false) String r) {
		String path = Page.myAuctionGoods;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser user = ActionUtil.checkSession4User(request.getSession());
			if(null == user){
				String jumpUrl = "/myAGList/"+auctionId;
				if(null != r)jumpUrl += "?r="+r;
				return Result.userSessionInvalid(modelMap, jumpUrl);
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("auctionId", auctionId);//在URL路径中获取的参数不为被自动获取，需要手动存入paramMap
			List<AuctionProfession> apList = apService.selectListByCondition(map);
			if(null != apList && apList.size()>0){
				modelMap.put("ap", apList.get(0));
			}
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/myAGList/"+auctionId, modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@RequestMapping(value="/professionSendGoods")
	public ModelAndView professionSendGoods(ModelMap modelMap,HttpServletRequest request
			,@RequestParam(required=false) String r) {
		String path = Page.professionSendGoods;
		try{
			JSONObject json = new JSONObject();
			modelMap = authCheckService.checkWxLogin(request, modelMap, json, true, r);
			BaseUser user = ActionUtil.checkSession4User(request.getSession());
			if(null == user){
				String jumpUrl = "/professionSendGoods";
				if(null != r)jumpUrl += "?r="+r;
				return Result.userSessionInvalid(modelMap, jumpUrl);
			}
			Integer userId = user.getId();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userId", userId);
			List<AuctionInst> aiList = aiService.selectListByCondition(map);
			if(null == aiList || aiList.size()<=0){
				path = Page.auctionInst;
				return new ModelAndView(path, modelMap);
			}
			AuctionInst ai = aiList.get(0);
			modelMap.put("instId", ai.getId());
		}catch(Exception e){
			path = Page.error;
			Result.catchError(e, logger, this.getClass().getName()+"/professionSendGoods", modelMap);
		}
		return new ModelAndView(path, modelMap);
	}
	
	@ResponseBody
	@RequestMapping(value="/rejectSendGoods", method=RequestMethod.POST)
	public JSONObject rejectSendGoods(HttpServletRequest request,@RequestParam Integer goodsId) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userId", userId);
			List<AuctionInst> aiList = aiService.selectListByCondition(map);
			if(null == aiList || aiList.size()<=0){
				json.put("status", "failure");
				json.put("msg", "你还没有开通拍卖专场");
				return Result.success(json);
			}
			AuctionInst ai = aiList.get(0);
			BaseGoods goods = goodsService.selectByPrimaryKey(goodsId);
			if(null == goods){
				json.put("status", "failure");
				json.put("msg", "该拍品已经被删除");
				return Result.success(json);
			}
			Integer status = goods.getMainStatus();
			if(null == status || status.intValue() != 74){
				json.put("status", "failure");
				json.put("msg", "该拍品目前已经不是送拍状态");
				return Result.success(json);
			}
			Integer linkId = goods.getLinkId();
			Integer instId = ai.getId();
			if(null == linkId || linkId.intValue() != instId.intValue()){
				json.put("status", "failure");
				json.put("msg", "该拍品目前已经不在您的送拍列表中");
				return Result.success(json);
			}
			BaseGoods newG = new BaseGoods();
			newG.setId(goods.getId());
			newG.setMainStatus(1);//店铺中
			goodsService.updateByPrimaryKeySelective(newG);
			json.put("status", "success");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR-rejectSendGoods-加载我的藏品数据列表出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getMyGoods", method=RequestMethod.POST)
	public JSONObject getMyGoods(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userId", userId);
			List<AuctionInst> aiList = aiService.selectListByCondition(map);
			if(null == aiList || aiList.size()<=0){
				json.put("status", "failure");
				json.put("msg", "你还没有开通拍卖专场");
				return Result.success(json);
			}
			AuctionInst ai = aiList.get(0);
			map.remove("userId");
			map.put("forAuctionAndSend", 1);//处于可拍卖状态和送拍状态
			map.put("for_userId", userId);
			map.put("for_linkId", ai.getId());//拍卖机构ID
			map.put("orderBy", "main_status DESC, A.id");
			map.put("ascOrdesc", "DESC");
			List<BaseGoods> goodsList = goodsService.selectListByCondition(map);
			json.put("status", "success");
			json.put("rows", goodsList);
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_getMyGoods_加载我的藏品数据列表出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getProfessionSendGoods", method=RequestMethod.POST)
	public JSONObject getProfessionSendGoods(HttpServletRequest request) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Integer userId = user.getId();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userId", userId);
			List<AuctionInst> aiList = aiService.selectListByCondition(map);
			if(null == aiList || aiList.size()<=0){
				json.put("status", "failure");
				json.put("msg", "你还没有开通拍卖专场");
				return Result.success(json);
			}
			AuctionInst ai = aiList.get(0);
			map.remove("userId");
			map.put("mainStatus", 74);//74:送拍中
			map.put("linkType", 1);//1:专场
			map.put("linkId", ai.getId());//拍卖机构ID
			List<BaseGoods> goodsList = goodsService.selectListByCondition(map);
			json.put("status", "success");
			json.put("rows", goodsList);
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_getProfessionSendGoods_加载拍场送拍数据列表出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getMyAutionGoods", method=RequestMethod.POST)
	public JSONObject getMyAutionGoods(HttpServletRequest request,
			@RequestParam(value="auctionId") Integer auctionId) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Map<String, Object> map = new HashMap<String, Object>();
			int userId = user.getId();
			map.put("buyerId", userId);
			map.put("auctionId", auctionId);
			List<AuctionGoods> goodsList = agService.selectListByCondition(map);
			json.put("status", "success");
			json.put("rows", goodsList);
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载我拍到的专场藏品列表出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getMyAutionGoodsByType", method=RequestMethod.POST)
	public JSONObject getMyAutionGoodsByType(HttpServletRequest request,Integer typeId) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Map<String, Object> map = new HashMap<String, Object>();
			int userId = user.getId();
			map.put("userId", userId);
			map.put("auctionId", typeId);
			List<BaseGoods> goodsList = goodsService.selectListByCondition(map);
			json.put("status", "success");
			json.put("rows", goodsList);
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载我拍到的专场藏品列表出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/loadProfessionGoods", method=RequestMethod.POST)
	public JSONObject loadProfessionGoods(HttpServletRequest request,@RequestParam Integer professionId) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("auctionId", professionId);
			String ids = agService.selectGoodsIdsOfProfession(map);
			if(null != ids && !"".equals(ids)){
				map.put("goodsIds", ids);
				List<BaseGoods> goodsList = goodsService.selectListByCondition(map);
				json.put("rows", goodsList);
			}
			json.put("status", "success");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载拍场列表出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getList", method=RequestMethod.POST)
	public JSONObject getList(HttpServletRequest request, @RequestParam String auctionSerial) {
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			Map<String, Object> map = CommonGenerator.getHashMap();
			map.put("auctionSerial", auctionSerial);
			//map.put("userId", user.getId());
			List<AuctionGoods> goodsList = agService.selectListByCondition(map);
			json.put("rows", goodsList);
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载专场拍场藏品列表出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/addOrUpdate", method=RequestMethod.POST)
	public JSONObject addOrUpdate(HttpServletRequest request,
			@RequestParam String apSerial,
			@RequestParam String auctionGoodsAry,
			@RequestParam String opt,
			@RequestParam(required=false) String payPassword){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			AuctionProfession ap = apService.selectBySerial(apSerial);
			Integer apId = ap.getId();
			apService.addOrUpdateAGList(json, user, null, auctionGoodsAry, apId, opt);
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ag/addOrUpdate", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/removeAG", method=RequestMethod.POST)
	public JSONObject removeAG(HttpServletRequest request, @RequestParam Integer agId){
		JSONObject json = new JSONObject();
		try {
			BaseUser user = ActionUtil.checkSession4User(request.getSession());//验证session中的user，存在即返回
			if(null == user){
				return Result.userSessionInvalid(json);//返回session过期的json提示
			}
			AuctionGoods ag = agService.selectByPrimaryKey(agId);
			if(null == ag){
				return Result.failure(json, "该拍品已经被移出本次拍卖", "ag_null");
			}else if(Check.integerNotEqual(ag.getUserId(), user.getId())){
				return Result.failure(json, "权限不足", "auth_lack");
			}
			AuctionProfession ap = apService.selectByPrimaryKey(ag.getAuctionId());
			if(null != ap && null != ap.getId()){
				AuctionProfession dbAP = apService.selectByPrimaryKey(ap.getId());//是否已经开始（1否，2是，3结束，4未提交，5提交审核中）
				if(null != dbAP && null != dbAP.getHaveBegun()){
					Integer haveBegun = dbAP.getHaveBegun();
					if( haveBegun == 5){
						return Result.failure(json, "本次拍卖正在审核中，无法移除拍品", "");
					}else if(haveBegun == 3){
						return Result.failure(json, "本次拍卖已经结束，无法移除拍品", "");
					}
				}
			}
			/*
			AuctionProfession ap = apService.selectByPrimaryKey(ag.getAuctionId());
			Integer haveBegun = ap.getHaveBegun();
			if(null != haveBegun && haveBegun == )*/
			agService.deleteByPrimaryKey(agId);
		}catch (Exception e) {
			Result.catchError(e, logger, this.getClass().getName()+"/ag/removeAG", json);
		}
		return Result.success(json);
	}
	
}
